package com.ly.algorithm.DataStructures.queue;

/**
 * @Classname ArrayQueue
 * @Description TODO
 * @Date 2020/4/20 16:22
 * @Author 冷心影翼
 */
public class ArrayQueue {

    private int maxSize;

    private int front;

    private int rear;

    private int arr[];

    public ArrayQueue(int maxSize) {
        this.maxSize = maxSize;
        front = 0;
        rear = 0;
        arr = new int[maxSize];
    }

    public boolean isEmpty() {
        return front == rear;
    }

    public boolean isFull() {
        return (rear+1)%maxSize == front;
    }

    //加入队列
    public void addQueue(int value) {
        if(isFull()) {
            throw new RuntimeException("队列已满");
        }
        arr[rear] = value;
        //队尾后移
        rear = (rear + 1)%maxSize;
    }

    //出队列
    public int get() {
        if(isEmpty()) {
            throw new RuntimeException("队列已空");
        }
        int value = arr[front];
        //队头后移动
        front = (front +1)%maxSize;
        return value;
    }

    //打印队列
    public void list() {
        if(isEmpty()) {
            throw new RuntimeException("队列已空");
        }
        //有效长度 front+(rear-front+maxSize)%maxSize
        for(int i=front+(rear-front+maxSize)%maxSize-1;i>=front;i--) {
            System.out.println(arr[i]);
        }
    }

    //得到队列头
    public int getHeader() {
        if(isEmpty()) {
            throw new RuntimeException("队列已空");
        }
        return arr[front];
    }

    public static void main(String[] args) {
        ArrayQueue queue = new ArrayQueue(4);
        queue.addQueue(1);
        queue.addQueue(2);
        queue.addQueue(3);
        queue.list();
        System.out.println("-------");
        System.out.println(queue.get());
        System.out.println(queue.get());
        System.out.println("-------");
        queue.addQueue(44);

        System.out.println(queue.getHeader());
        System.out.println("-------");
        queue.list();
    }
}
